import { tools } from "./tools/tools";
import fs from 'fs';

export namespace trans_res_generator {
	export class TransResGen {
		constructor(root: string) {
			this.curRoot = root;

			this.GenLangCfg().then(result => {
				if (!result) {
					console.warn('cfg file not exit');
					return;
				}
				this.GenResAssets();
			})
		}

		private async GenLangCfg(): Promise<boolean> {

			let baseCfg = tools.QueryEgretProperties(this.curRoot);
			let cfgPath = `${this.curRoot}/${baseCfg?.localization?.config_path}`;
			if (!fs.existsSync(cfgPath)) {
				return false;
			}

			let lanCfgRaw = fs.readFileSync(cfgPath, { encoding: 'utf-8' });
			let lanCfg = JSON.parse(lanCfgRaw || '{}') as tools.TRANS_CFG_TYPE;

			let resPath = baseCfg?.path || tools.DEF_RES_PATH;
			let files: string[];
			let tmp: string[];
			for (let lang of lanCfg.to_languages) {
				for (let folder of lanCfg.include_folder) {
					files = await tools.GlobFile([`**.*`], '', { nodir: true, cwd: `${this.curRoot}/${resPath}/${folder}/${lang}` });
					this.langCfgArr[lang] = this.langCfgArr[lang] || {};
					for (let file of files) {
						tmp = file.split('/');
						this.langCfgArr[lang][tmp[tmp.length - 1]] = `${folder}/${lang}/${file}`;
					}
				}
			}

			return true;
		}

		private GenResAssets(): void {
			let baseCfg = tools.QueryEgretProperties(this.curRoot);
			let winCfg = tools.QueryWingProperties(this.curRoot);
			let lanCfgRaw = fs.readFileSync(`${this.curRoot}/${baseCfg?.localization?.config_path}`, { encoding: 'utf-8' });

			let lanCfg = JSON.parse(lanCfgRaw || '{}') as tools.TRANS_CFG_TYPE;
			let resPath = baseCfg?.path || tools.DEF_RES_PATH;
			let cfgRefPath: string;
			let cfgPath: string;
			let tmp: string[];
			let fileName: string;
			let findWing: boolean;
			for (let lan of lanCfg.to_languages) {
				for (let file of lanCfg.cfg_file_set) {
					cfgPath = `${this.curRoot}/${resPath}/${file.file}`;
					if (!fs.existsSync(cfgPath)) {
						continue;
					}
					let org = JSON.parse(fs.readFileSync(cfgPath, { encoding: 'utf-8' }) || '{}') as tools.RES_FILE_TYPE;
					for (let res of org.resources) {
						tmp = res.url.split('/');
						fileName = tmp[tmp.length - 1];
						this.langCfgArr[lan][fileName] && (res.url = this.langCfgArr[lan][fileName]);

						if ('rescfg' == res.type) {
							for (let tmp of lanCfg.cfg_file_set) {
								if (tmp.file == res.url) {
									res.url = this.FormatStr(tmp.to_file, { lang: lan });
									break;
								}
							}
						}
					}
					findWing = false;
					cfgRefPath = `${resPath}/${this.FormatStr(file.to_file, { lang: lan })}`;
					org.resources.sort((a, b) => {
						return tools.HashNum(a.name) - tools.HashNum(b.name);
					});
					fs.writeFileSync(`${this.curRoot}/${cfgRefPath}`, JSON.stringify(org, null, '\t'), { encoding: 'utf-8', flag: 'w+' });
					for (let cfg of winCfg.resourcePlugin.configs) {
						if (cfg.configPath == cfgRefPath) {
							findWing = true;
						}
					}
					if (!findWing) {
						winCfg.resourcePlugin.configs.push({ configPath: cfgRefPath, relativePath: `${resPath}/` });
					}
				}
			}

			tools.SaveWingProperties(this.curRoot, winCfg);
		}

		private FormatStr(str: string, data: { [key: string]: string }): string {
			if (!str) {
				return str;
			}
			return str.replace(/\{(\S+?)\}/g, (key, arg) => {
				return data[arg] || key;
			})
		}

		private langCfgArr: { [lang: string]: { [fileName: string]: string } } = {};
		private curRoot: string;
	}
}